package com.masterrabbit.gyf.Controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.masterrabbit.common.core.utils.uuid.UUID;
import com.masterrabbit.gyf.Service.TicketService;
import com.masterrabbit.gyf.Utils.R;
import com.masterrabbit.gyf.domain.Coupons;
import com.masterrabbit.gyf.domain.CouponsMerchants;
import com.masterrabbit.gyf.domain.UserCoupons;
import com.masterrabbit.gyf.mapper.CouponsMapper;
import com.masterrabbit.gyf.mapper.CouponsMerchantsMapper;
import com.masterrabbit.gyf.mapper.UserCouponsMapper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/ticket")
public class TicketController {
    @Autowired
    private TicketService ticketService;

    @Autowired
    private CouponsMerchantsMapper couponsMerchantsMapper;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private CouponsMapper couponsMapper;
    @Autowired
    private UserCouponsMapper userCouponsMapper;
    /**
     * 抢票接口
     */
    @GetMapping("/grab")
    public R grabTicket(@RequestParam int userId,@RequestParam int MerchantId,
                             @RequestParam String key,@RequestParam String createTime,
                             @RequestParam String endTime) {
        String successkey ="successTicket:"+MerchantId+":"+
                createTime;
        System.out.println("打印一下参数key:"+key);
        System.out.println("打印一下successkey"+successkey);

        //验证用户是否已经抢过票
        Boolean member = redisTemplate.opsForSet().isMember(successkey, userId);
        if(Boolean.TRUE.equals(member)){
            System.out.println("你已经抢过票了");
            return R.fail("你已经抢过票了,不可再抢");
        }else{
            String ticket = ticketService.grabTicket(key);


            //判断这个用户是是否抢过票了

            if (ticket != null) {
                //生成现在的时间

                Coupons coupons = JSONObject.parseObject(ticket, Coupons.class);
                //用户成功抢到了票,开始往redis中插入数据记录
                redisTemplate.opsForSet().add(successkey, userId);
                //设置过期时间
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime time = LocalDateTime.parse(endTime, formatter);
                ZonedDateTime zonedDateTime = time.atZone(ZoneId.of("Asia/Shanghai"));
                Date date = Date.from(zonedDateTime.toInstant());
                redisTemplate.expireAt(successkey, date);

                UserCoupons userCoupons = new UserCoupons();
                userCoupons.setCouponCode(coupons.getCouponCode());
                userCoupons.setUserId(userId);
                userCoupons.setCouponId(coupons.getCouponId());
                userCoupons.setStatus(coupons.getStatus());

                HashMap<String, Object> map = new HashMap<>();
                map.put("userCoupons", userCoupons);
                map.put("coupons", coupons);
                rabbitTemplate.convertAndSend("successex1","",JSONObject.toJSONString(map));
                return R.ok(ticket);
            } else {
                System.out.println("打印一下ticket:"+ticket);
                return R.fail("票已售罄！");
            }
        }

    }

    /**
     * 初始化票数
     */
    @RequestMapping("/init")
    public String initTickets(@RequestBody JSONObject obj) {
                String couponsJson = obj.getString("coupons");
        String createTime = obj.getString("now");
        Coupons coupons = JSONObject.parseObject(couponsJson, Coupons.class);

        List<String> tickets = new ArrayList<>();// 生成 10 张票的编号
        for (int i = 0; i < coupons.getTotalQuantity(); i++) {
            coupons.setCouponCode(UUID.randomUUID().toString());
            tickets.add(JSONObject.toJSONString(coupons));
        }

        //开始计算redis存活时间
        LocalDateTime startTime = coupons.getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        LocalDateTime endTime=coupons.getEndTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        long seconds = Duration.between(startTime, endTime).getSeconds();


        ticketService.initTickets(tickets,seconds,createTime,coupons.getMerchantId()); // 初始化票列表
        System.out.println("打印一下coupons:" + coupons);
        System.out.println("打印一下创建时间"+createTime);


        //上面是生成优惠券,下面是生成优惠券的类型，用于展示在前端
        CouponsMerchants couponsMerchants = new CouponsMerchants();
        couponsMerchants.setKey("tickets:"+coupons.getMerchantId()+":"+createTime);
        couponsMerchants.setCouponName(coupons.getCouponName());
        couponsMerchants.setCouponType(coupons.getCouponType());
        couponsMerchants.setConditionMet(coupons.getConditionMet());
        couponsMerchants.setDiscountAmount(coupons.getDiscountAmount());
        couponsMerchants.setDiscountRate(coupons.getDiscountRate());
        couponsMerchants.setMerchantsId(coupons.getMerchantId());
        couponsMerchants.setCount(coupons.getTotalQuantity());
        couponsMerchants.setStartTime(coupons.getStartTime());
        couponsMerchants.setEndTime(coupons.getEndTime());
        couponsMerchants.setStartValidTime(coupons.getValidStartTime());
        couponsMerchants.setEndValidTime(coupons.getValidEndTime());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime time = LocalDateTime.parse(createTime, formatter);
        ZonedDateTime zonedDateTime = time.atZone(ZoneId.of("Asia/Shanghai"));
        Date time2 = Date.from(zonedDateTime.toInstant());
        couponsMerchants.setCreateTime(time2);
        int insert = couponsMerchantsMapper.insert(couponsMerchants);
        //开始往redis存储信息
        //将时间转为时间戳
        Date endTime1 = couponsMerchants.getEndTime();
        long time1 = endTime1.getTime();
        //存入操作
        redisTemplate.opsForZSet().add("showticket",couponsMerchants,time1);
        //查询操作
        redisTemplate.opsForZSet().removeRangeByScore("showticket",0,new Date().getTime());
        Set<Object> showticket = redisTemplate.opsForZSet().range("showticket", 0, -1);
        System.out.println("开始显示redis集合中的所有zset数据");
        System.out.println(showticket);
        System.out.println("打印一下存入时候的时间戳");
        System.out.println(time1);
        return "票数初始化成功！";
    }


    /**
     * 前端获取可抢优惠券列表
     */
    @GetMapping("/getAll")
    public R getAll() {
        //开始请求redis,获取所有优惠券的列表
        //先把停止放券的给删除掉
        redisTemplate.opsForZSet().removeRangeByScore("showticket",0,new Date().getTime());
        Set<Object> showticket = redisTemplate.opsForZSet().range("showticket", 0, -1);
        if(!showticket.isEmpty()){
            return R.ok(showticket);
        }else{
            return R.fail("暂无可抢的优惠券");
        }
    }

    /**
     * 查看用户的可用优惠券
     */
    @GetMapping("/getUserTicket")
    public R getUserTicket(@RequestParam int userId,@RequestParam int status) {
        //首先通过用户id查出该用户拥有的优惠券
        LambdaQueryWrapper<UserCoupons> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserCoupons::getUserId,userId).eq(UserCoupons::getStatus,status);
        List<UserCoupons> userCouponsList = userCouponsMapper.selectList(wrapper);
        if (!userCouponsList.isEmpty()) {
            List<Integer> idlist = userCouponsList.stream().filter(userCoupons1 ->
                            userCoupons1.getUserId() == userId
                                    && userCoupons1.getStatus() == status).
                    map(UserCoupons::getCouponId).collect(Collectors.toList());
            List<Coupons> coupons = couponsMapper.selectByIds(idlist);
            return R.ok(coupons);
        }else{
            return R.ok(null);
        }

    }


}
